<template>
  <div class="p-5 pt-0">
    <el-row :gutter="20">
      <el-col :span="8" :xs="24">
        <el-card>
          <template #header>
            <span>个人信息</span>
          </template>

          <el-skeleton v-if="loading" :rows="10" animated/>
          <el-row v-else class="flex justify-center">

            <el-col class="inline-flex justify-center">

              <el-upload
                  class="avatar-uploader"
                  action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
              >
                <el-image :preview-src-list="[data.user.avatar]" class="rounded-xl" style="width: 100px; height: 100px;"
                          :src="data.user.avatar" fit="fill">
                  <template #error>
                    <el-image class="rounded-xl"
                              style="width: 100px; height: 100px;"
                              src="src/assets/images/avatar.png"
                              fit="fill"/>
                  </template>
                </el-image>
              </el-upload>


            </el-col>

            <el-descriptions
                :column="1"
                :size="store.layoutSize"
                border
                style="width: 100%;"
                class="mt-3"
            >
              <el-descriptions-item>
                <template #label>
                  <div>
                    <el-icon>
                      <user/>
                    </el-icon>
                    用户名
                  </div>
                </template>
                {{ data.user.userName }}
              </el-descriptions-item>

              <el-descriptions-item>
                <template #label>
                  <div>
                    <el-icon>
                      <iphone/>
                    </el-icon>
                    手机号
                  </div>
                </template>
                {{ data.user.phonenumber }}
              </el-descriptions-item>

              <el-descriptions-item>
                <template #label>
                  <div>
                    <el-icon>
                      <Message/>
                    </el-icon>
                    邮箱
                  </div>
                </template>
                {{ data.user.email }}
              </el-descriptions-item>

              <el-descriptions-item>
                <template #label>
                  <div>
                    <el-icon>
                      <Share/>
                    </el-icon>
                    部门
                  </div>
                </template>
                {{ data.dept.deptName }}
              </el-descriptions-item>

              <el-descriptions-item>
                <template #label>
                  <div>
                    <el-icon>
                      <Menu/>
                    </el-icon>
                    角色
                  </div>
                </template>
                <el-tag class="mr-1" :size="store.layoutSize" v-for="role in data.roleGroup" :key="role.roleId">{{
                    role.roleName
                  }}
                </el-tag>
              </el-descriptions-item>

              <el-descriptions-item>
                <template #label>
                  <div>
                    <el-icon>
                      <Calendar/>
                    </el-icon>
                    创建时间
                  </div>
                </template>
                {{ moment(data.user.createTime).format('YYYY-MM-DD HH:mm:ss') }}
              </el-descriptions-item>

            </el-descriptions>
          </el-row>

        </el-card>
      </el-col>
      <el-col :span="16" :xs="24">
        <el-card>
          <template #header>
            <span>基本资料</span>
          </template>

          <el-skeleton v-if="loading" :rows="7" animated/>
          <el-tabs v-else v-model="data.activeTab">
            <el-tab-pane label="基本资料" name="userinfo">

              <el-form ref="infoFormRef" :model="data.user" :rules="userRules" label-width="80px">
                <el-form-item label="用户昵称" prop="nickName">
                  <el-input v-model="data.user.nickName" maxlength="30"/>
                </el-form-item>
                <el-form-item label="手机号码" prop="phonenumber">
                  <el-input v-model="data.user.phonenumber" maxlength="11"/>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="data.user.email" maxlength="50"/>
                </el-form-item>
                <el-form-item label="性别">
                  <el-radio-group v-model="data.user.sex">
                    <el-radio label="0">男</el-radio>
                    <el-radio label="1">女</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" :size="store.layoutSize" @click="submitInfo(infoFormRef)">保存</el-button>
                  <el-button type="danger" :size="store.layoutSize" @click="router.push('/')">关闭</el-button>
                </el-form-item>
              </el-form>

            </el-tab-pane>
            <el-tab-pane label="修改密码" name="resetPwd">

              <el-form ref="passFormRef" :model="data.pass" :rules="passRules" label-width="80px">
                <el-form-item label="旧密码" prop="oldPassword">
                  <el-input v-model="data.pass.oldPassword" placeholder="请输入旧密码" type="password" show-password/>
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                  <el-input v-model="data.pass.newPassword" placeholder="请输入新密码" type="password" show-password/>
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input v-model="data.pass.confirmPassword" placeholder="再次输入新密码" type="password"
                            show-password/>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" :size="store.layoutSize" @click="passSubmit(passFormRef)">保存</el-button>
                  <el-button type="danger" :size="store.layoutSize" @click="router.push('/')">关闭</el-button>
                </el-form-item>
              </el-form>

            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import {reactive, ref} from "vue";
import {checkPassword, saveUserInfo, selectUserById} from "@/api/user";
import {useStore} from "@/store";
import moment from "moment";
import {ElNotification, FormInstance, FormRules} from "element-plus";
import {useRouter} from "vue-router";

const store = useStore()

const router = useRouter()

const infoFormRef = ref<FormInstance>()
const passFormRef = ref<FormInstance>()

const data = reactive({
  user: {},
  dept: {},
  roleGroup: [],
  activeTab: "userinfo",
  pass: {
    oldPassword: null,
    newPassword: null,
    confirmPassword: null
  }
})

const loading = ref(true)

//获取用户信息
selectUserById(store.getUser.userId).then(result => {
  data.user = result.data.data
  data.dept = result.data.data.sysDept
  data.roleGroup = result.data.data.roles
  loading.value = false
})

//表单验证
const userRules = reactive<FormRules>({
  nickName: [
    {required: true, message: "用户昵称不能为空", trigger: "blur"}
  ],
  email: [
    {required: true, message: "邮箱地址不能为空", trigger: "blur"},
    {
      type: "email",
      message: "请输入正确的邮箱地址",
      trigger: ["blur", "change"]
    }
  ],
  phonenumber: [
    {required: true, message: "手机号码不能为空", trigger: "blur"},
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur"
    }
  ]
})

const equalToPassword = (rule: any, value: any, callback: any) => {
  if (data.pass.newPassword !== value) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};

const equalToPassword2 = (rule: any, value: any, callback: any) => {
  checkPassword({userId: data.user.userId, password: data.pass.oldPassword}).then(result => {
    if (result.data.code == 200) {
      callback()
    } else {
      callback(new Error("旧密码不正确"));
    }
  })
};

const passRules = reactive<FormRules>({
  oldPassword: [
    {required: true, message: "旧密码不能为空", trigger: "blur"},
    {required: true, validator: equalToPassword2, trigger: "blur"}
  ],
  newPassword: [
    {required: true, message: "新密码不能为空", trigger: "blur"},
    {min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur"}
  ],
  confirmPassword: [
    {required: true, message: "确认密码不能为空", trigger: "blur"},
    {required: true, validator: equalToPassword, trigger: "blur"}
  ]
})

//提交修改表单
const submitInfo = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      saveUserInfo({
        userId: data.user.userId,
        nickName: data.user.nickName,
        phonenumber: data.user.phonenumber,
        email: data.user.email,
        sex: data.user.sex,
        updateBy: store.getUser.userName
      }).then(result => {
        selectUserById(data.user.userId).then(result => {
          store.setUser(result.data.data)
        })
        if (result.data.code === 200) {
          ElNotification({
            message: result.data.msg,
            type: 'success'
          })
        } else {
          ElNotification({
            message: result.data.msg,
            type: 'error'
          })
        }
      })
    }
  })
}

//提交修改表单
const passSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      saveUserInfo({
        userId: data.user.userId,
        password: data.pass.newPassword
      }).then(result => {
        if (result.data.code === 200) {
          ElNotification({
            message: result.data.msg,
            type: 'success'
          })
        } else {
          ElNotification({
            message: result.data.msg,
            type: 'error'
          })
        }
        data.pass.oldPassword = null
        data.pass.confirmPassword = null
        data.pass.newPassword = null
      })
    }
  })
}
</script>

<style scoped>

</style>
